from PySide6.QtWidgets import QMainWindow,QMessageBox,QApplication, QTableWidgetItem, QHeaderView
from PySide6.QtCore import  QThread, Signal,Qt

import configparser
from pathlib import Path
import sys
import datetime

from app.connect_service import ConnectorService
from app.ui.pause_window import PauseWindow
if getattr(sys, 'frozen', False): 
    root_dir = Path(sys.executable).parent 
else:
    root_dir=Path(__file__).resolve().parent.parent

class MainWindowConnect(QMainWindow):
    startTask = Signal(str, dict)
    def __init__(self,ui=None):
        super().__init__()
        self.ui = ui
        self.stopui=PauseWindow()
        self.config_init()
        self._init_thread()
        self.text_browser_init()
        self._connect_signals()
        self.reflush_pb_clicked()

# region 配置初始化
    def config_init(self):
        self.config = configparser.ConfigParser()
        self.config_file = root_dir / 'config.ini'
        if not self.config_file.exists():
            self._create_default_config()
        else:
            self.config.read(self.config_file,encoding="utf-8")
        self._get_scale_config()

    def _create_default_config(self):
        """创建默认配置文件"""
        self.config['SETTING'] = {
            'scale': '1.0', 
            'key_a': 'a', 
            'key_d': 'd',
            'key_w': 'w',
            'key_s': 's',
            'key_k': 'k',
            'key_attack': 'l',
            '神秘商人': '1',
            '万灵塔':"1,2,3,4"
        }
        with open(self.config_file, 'w',encoding="utf-8") as f:
            self.config.write(f)

    def _get_scale_config(self):
        """读取配置"""
        try:
            # 读取缩放比例
            self.scale_num = self.config.getfloat('SETTING', 'scale')
            
            # 读取按键映射
            self.key_map = {
                'key_a': self.config.get('SETTING', 'key_a', fallback='a'),
                'key_d': self.config.get('SETTING', 'key_d', fallback='d'),
                'key_w': self.config.get('SETTING', 'key_w', fallback='w'),
                'key_s': self.config.get('SETTING', 'key_s', fallback='s'),
                'key_k': self.config.get('SETTING', 'key_k', fallback='k'),
                'key_attack': self.config.get('SETTING', 'key_attack', fallback='l')
            }
            
        except (configparser.NoSectionError, configparser.NoOptionError):
            # 创建包含默认值的完整配置
            self.config['SETTING'] = {
                'scale': '1.0',
                'key_a': 'a',
                'key_d': 'd',
                'key_w': 'w', 
                'key_s': 's',
                'key_k': 'k',
                'key_attack': 'l'
            }
            with open(self.config_file, 'w',encoding="utf-8") as f:
                self.config.write(f)
            self.scale_num = 1.0
            self.key_map = {k.split('_')[1]: v for k, v in self.config['SETTING'].items() if k.startswith('key_')}
     
            
        except ValueError:
            print("配置参数格式错误，已重置为默认值")
            self.scale_num = 1.0
            self.key_map = {'a': 'a', 'd': 'd', 'w': 'w', 's': 's', 'k': 'k', 'attack': 'l'}
            return 1.0
# endregion



# region 线程相关函数
    def _init_thread(self):
        # 确保线程完全释放
        self.release_thread()
        
        # 创建新对象
        self.worker_thread = QThread()
        self.worker = ConnectorService(self.key_map)
        self.worker.moveToThread(self.worker_thread)
        
        # 精确连接信号（使用关键字参数）
        self.startTask.connect(self.worker.execute_task)
        self.worker.get_scale.connect(self._set_scale_num)
        self.worker.logMessage.connect(self._show_log_message)
        self.worker.finished.connect(self._finished_task)
        
        # 启动线程
        self.worker_thread.start()

    def release_thread(self):
        """暴力终止线程（类似kill -9）"""
        if hasattr(self, 'worker_thread'):
            try:
                # 强制断开所有信号
                self.startTask.disconnect()
                self.worker.get_scale.disconnect()
                self.worker.progressUpdated.disconnect()
                self.worker.logMessage.disconnect()
                self.worker.finished.disconnect()
            except Exception as e:
                self._show_log_message(f"强制断开信号失败: {e}")
            
            # 立即终止线程
            self.worker_thread.terminate()  # 关键暴力终止
            self.worker_thread.wait(1000)   # 等待1秒确保终止
            
            # 强制删除对象
            if hasattr(self, 'worker'):
                self.worker.deleteLater()
            self.worker_thread.deleteLater()
            
            del self.worker
            del self.worker_thread
            
            QApplication.processEvents()  # 强制刷新事件队列
# endregion

# region 信号槽连接
    def _connect_signals(self):

        self.stopui.stop_signal.connect(self.connect_stop_Signal)
        # 连接按钮点击事件到槽函数
        self.ui.wlt_pb.clicked.connect(lambda: self._emit_task('wlt'))
        self.ui.zld_pb.clicked.connect(lambda: self._emit_task('zld'))
        self.ui.douchong_challenge_pb.clicked.connect(lambda: self._emit_task('douchong_challenge'))
        self.ui.Mysterious_Merchant_pb.clicked.connect(lambda: self._emit_task('Mysterious_Merchant'))
        self.ui.baoku_pb.clicked.connect(lambda: self._emit_task('baoku'))
        self.ui.synthesis_gemstone_pb.clicked.connect(lambda: self._emit_task('synthesis_gemstone'))
        self.ui.signin_pb.clicked.connect(lambda: self._emit_task('signin'))
        self.ui.donate_pb.clicked.connect(lambda: self._emit_task('donate'))
        self.ui.zhuzhan_pb.clicked.connect(lambda: self._emit_task('zhuzhan'))
        self.ui.douchong_pb.clicked.connect(lambda: self._emit_task('douchong'))
        self.ui.wanshou_pb.clicked.connect(lambda: self._emit_task('wanshou'))
        self.ui.fixed_ui.every_day_pb.clicked.connect(lambda: self._emit_task('every_day'))
        self.ui.fixed_ui.scale_match_pb.clicked.connect(lambda: self._emit_task('scale'))
        self.ui.fixed_ui.pb_record.clicked.connect(lambda: self._emit_task('record'))
        self.ui.fixed_ui.pb_execute.clicked.connect(lambda: self._emit_task('execute'))
        self.ui.fixed_ui.tw_script.itemChanged.connect(self.on_table_item_changed)

        self.ui.fixed_ui.tw_script.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.fixed_ui.tw_script.customContextMenuRequested.connect(self.show_table_context_menu)

    def _emit_task(self, task_name):
        """收集参数并发射任务信号"""
        self.ui.hide()
        self.stopui.show()
        params = {}
        if task_name == 'wlt':
            params = {
                'spin_box_value': self.ui.wlt_spin_box.value(),
                'selected_index': self.ui.wlt_combo_box.currentIndex() + 1,
                'scale': self.scale_num
            }
        elif task_name == 'zld':
            params = {'scale': self.scale_num}
        elif task_name == 'every_day':
            params = {'scale': self.scale_num}
        elif task_name == 'Mysterious_Merchant':
            params = {
               'buy_index': self.ui.Mysterious_Merchant_combo_box.currentIndex() + 1,
               'scale': self.scale_num
            }
        elif task_name == 'baoku':
            params = {'scale': self.scale_num}
        elif task_name == 'synthesis_gemstone':
            params = {
                'check_boxes': self.ui.synthesis_gemstone_check_boxes,
                'scale': self.scale_num
            }
        elif task_name == 'signin':
            params = {'scale': self.scale_num}
        elif task_name == 'donate':
            params = {
                'donate_count': self.ui.donate_spin_box.value(),
                'scale': self.scale_num
            }
        elif task_name == 'zhuzhan':
            params = {
                'kunrun_map_num': self.ui.zhuzhan_combo_box.currentIndex()+1,   
                'scale': self.scale_num
            }
        elif task_name == 'douchong':
            continue_execution = self.get_time_choose()
            params = {
                'continue_execution': continue_execution,
                'scale': self.scale_num
            }
        elif task_name == 'wanshou':
            params = {'scale': self.scale_num}
        elif task_name == 'scale':
            pass
        elif task_name == 'douchong_challenge':
            params = {
                'selected_index': self.ui.douchong_challenge_combo.currentIndex() + 1,
                'scale': self.scale_num
            }
        elif task_name == 'record':
            params = {
                'scale': self.scale_num,
            }
        elif task_name == 'execute':
            params = {
                'execute_count': self.ui.fixed_ui.spb_execute.value(),
                'filename': self.ui.fixed_ui.tw_script.currentItem().text(),
                'scale': self.scale_num,
            }
        self.startTask.emit(task_name, params)
# endregion

# region 显示初始化
    def text_browser_init(self):
        """
        文本框初始化
        """
        self.ui.fixed_ui.textBrowser.setText("软件启动成功！！！")
        self.ui.fixed_ui.textBrowser.append("欢迎使用！！！")
        self.ui.fixed_ui.textBrowser.append(f"当前缩放比例为：{self.scale_num}")
        self.ui.fixed_ui.textBrowser.setReadOnly(True)  # 设置文本框只读
        self.ui.fixed_ui.textBrowser.ensureCursorVisible()  # 设置光标可见
# endregion

# region 显示日志
    def _show_log_message(self, message):
        """显示日志消息"""
        self.ui.fixed_ui.textBrowser.setReadOnly(False)
        self.ui.fixed_ui.textBrowser.append(message)
        self.ui.fixed_ui.textBrowser.setReadOnly(True)
        self.ui.fixed_ui.textBrowser.ensureCursorVisible()
        self.ui.fixed_ui.textBrowser.verticalScrollBar().setValue(
            self.ui.fixed_ui.textBrowser.verticalScrollBar().maximum()
        )
        self.repaint()
        self.ui.update()
# endregion

# region 参数设置
    def _set_scale_num(self, scale: float):
        self.scale_num = scale
        self.config.set('SETTING', 'scale', str(scale))
        with open(self.config_file, 'w',encoding='utf-8') as configfile:
            self.config.write(configfile)
# endregion

# region 时间选择弹窗
    def get_time_choose(self):
        continue_execution = False
        now = datetime.datetime.now()

        # 判断是否在指定时间段
        if now.weekday() == 6:
            start_time = now.replace(hour=23, minute=0, second=0, microsecond=0)
            end_time = now.replace(hour=23, minute=55, second=0, microsecond=0)
            continue_execution = start_time <= now < end_time

        # 询问是否继续
        if not continue_execution:
            day_of_week = ["星期一", "星期二", "星期三", "星期四",
                       "星期五", "星期六", "星期日"][now.weekday()]
            hour = now.hour
            minute = now.minute

            msg_box = QMessageBox(self)
            msg_box.setWindowTitle("温馨提示:")
            msg_box.setText(f"现在是{day_of_week} {hour}:{minute}，不建议反击，是否继续反击？")

            msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            # 自定义按钮文本
            msg_box.button(QMessageBox.Yes).setText("继续反击")
            msg_box.button(QMessageBox.No).setText("取消反击")
            result = msg_box.exec()
            continue_execution = result == QMessageBox.Yes

        return continue_execution
# endregion

# region 刷新
    def reflush_pb_clicked(self):
        # 确保script_dir目录存在
        script_dir = root_dir / 'script_dir'
        script_dir.mkdir(parents=True, exist_ok=True)
        
        print(script_dir)

        # 获取目录中的所有文件
        files = []
        if script_dir.exists():
            files = [f.name for f in script_dir.iterdir() if f.is_file()]
        
        # 清空表格
        self.ui.fixed_ui.tw_script.setRowCount(0)
        
        # 设置表格列数和标题
        self.ui.fixed_ui.tw_script.setColumnCount(1)
        self.ui.fixed_ui.tw_script.setHorizontalHeaderLabels(["脚本文件"])
        
        # 添加文件到表格
        for row, filename in enumerate(files):
            self.ui.fixed_ui.tw_script.insertRow(row)
            item = QTableWidgetItem(filename)
            # 存储原始文件名用于修改对比
            item.setData(Qt.UserRole, filename)
            # 设置单元格可编辑
            item.setFlags(item.flags() | Qt.ItemIsEditable)
            self.ui.fixed_ui.tw_script.setItem(row, 0, item)
        
        # 调整列宽以适应内容
        self.ui.fixed_ui.tw_script.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

# endregion

# region 脚本重命名
    def on_table_item_changed(self, item):
        # 只处理第一列的修改
        if item.column() != 0:
            return
        
        script_dir = root_dir / 'script_dir'
        old_name = item.data(Qt.UserRole)
        new_name = item.text().strip()
        
        # 检查文件名是否有变化
        if old_name == new_name:
            return
        
        # 验证新文件名
        if not new_name:
            self._show_log_message("错误：文件名不能为空")
            item.setText(old_name)
            return
        
        # 检查文件是否存在
        old_path = script_dir / old_name
        new_path = script_dir / new_name
        
        if not old_path.exists():
            self._show_log_message(f"错误：原始文件 '{old_name}' 不存在")
            item.setText(old_name)
            return
        
        if new_path.exists():
            self._show_log_message(f"错误：文件 '{new_name}' 已存在")
            item.setText(old_name)
            return
        
        # 执行重命名
        try:
            old_path.rename(new_path)
            item.setData(Qt.UserRole, new_name)
            self._show_log_message(f"成功重命名：'{old_name}' -> '{new_name}'")
            # 刷新表格以确保显示正确
            self.reflush_pb_clicked()
        except Exception as e:
            self._show_log_message(f"重命名失败：{str(e)}")
            item.setText(old_name)
# endregion

# region 脚本菜单
    def show_table_context_menu(self, position):
        """显示表格的上下文菜单"""
        from PySide6.QtWidgets import QMenu
        menu = QMenu(self)
        menu.addAction("刷新", self.reflush_pb_clicked)
        menu.addAction("删除", lambda: self.delete_selected())
        menu.exec_(self.ui.fixed_ui.tw_script.mapToGlobal(position))
# endregion
        
# region 删除选中行
    def delete_selected(self):
        """删除选中的行及对应的脚本文件"""
        selected_rows = self.ui.fixed_ui.tw_script.selectionModel().selectedRows()
        if not selected_rows:
            return
        
        script_dir = root_dir / 'script_dir'
        
        # 先删除对应的文件
        for index in selected_rows:
            row = index.row()
            item = self.ui.fixed_ui.tw_script.item(row, 0)
            if item:
                filename = item.data(Qt.UserRole)
                file_path = script_dir / filename
                if file_path.exists():
                    try:
                        file_path.unlink()
                        self._show_log_message(f"成功删除文件: {filename}")
                    except Exception as e:
                        self._show_log_message(f"删除文件失败: {filename}, 错误: {str(e)}")
                else:
                    self._show_log_message(f"文件不存在: {filename}")
        
        # 刷新表格以更新显示
        self.reflush_pb_clicked()

# region 任务完成
    def _finished_task(self):
        """
            任务完成后的处理
        """
        self.ui.show()  
        self.stopui.hide()
        self.activateWindow() 
#  endregion

# region 停止信号
    def connect_stop_Signal(self):
        self._finished_task()
        self.release_thread()  # 先释放旧线程
        self._init_thread()     # 再重新初始化线程
        self._show_log_message("强制重启完成")
# endregion